package custom;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.menhoo.menhoolibrary.R;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.AndroidFileUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.io.FileUtils;
import com.example.menhoo.toollibrary.common.utils.SdCardUtil;
import com.example.menhoo.toollibrary.common.utils.VibrateUtil;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.cache.MD5FileNameGenerator;
import com.lidroid.xutils.util.LogUtils;
import com.rey.material.widget.ProgressView;
import com.rey.material.widget.Slider;
import com.viewpagerindicator.CirclePageIndicator;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import application.UIApplication;
import application.UIHttpURL;
import frame.UIActivity;
import interfaces.IDownLoadListener;
import model.DownloadDbModel;
import model.FileInfo;
import model.ImageInfo;
import service.DownLoadService;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * AndroidManifest.xml 中 , 要注册
 *	Intent it = new Intent(this,ScaleImage.class);// 创建Intent对象
 *	it.putExtra("url", String[] url数组);
 *	it.putExtra("title", "要显示的标题");
 *	it.putExtra("currPage", 打开之后要定位的页数,int 类型);
 *	startActivity(it);
 */
public class ScaleImagesActivity extends UIActivity{

    /**
     * 图片页数大于minNavigationPage才会显示导航List
     */
    private int minNavigationPage=9;
    /**
     * 是否显示标题栏的标识变量
     */
    boolean F=true;

    DrawerLayout main_dl;
    LinearLayout linearLayoutMainPage,linearLayoutTitlebar,titlebar_layout_custom_cnx;
    ListView listView;
    FrameLayout main_fl_drawer;
    ImageButton button;
    TextView titlebar_tv_title_text,titlebar_tv_title_subtext;
    ImageButton titlebar_btn_back;

    List<String> urlList;
    List<ScalePageModel> pagesList;
    int DocPages,CurrPage=1;
    ViewPager mViewPager;
    ScalePagesAdapter spAdapter=null;
    CirclePageIndicator indicator;


    private FileInfo fileInfo=null;
    private ImageInfo imageInfo=null;


    public class ScalePageModel {
        public int Page;
        public String Name;
        public String Url;
        public boolean isSelect=false;
    }

    @Override
    public void beforeOnCreate() {
        super.beforeOnCreate();
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            fileInfo=(FileInfo)getIntent().getExtras().getSerializable("fileInfo");
//            fileInfo.downloadUrl = UIHttpURL.getWebSiteFullUrl(fileInfo.downloadUrl);
//            fileInfo.thumbUrl = UIHttpURL.getWebSiteFullUrl(fileInfo.thumbUrl);
        }
        catch (Exception e){
        }
        try{
            imageInfo=(ImageInfo)getIntent().getExtras().getSerializable("imageInfo");
        }
        catch (Exception e){
            MessageUtil.showShortToast(this,"打开图片失败");
            onBackPressed();
        }

        try
        {
            DocPages = imageInfo.urls.length;
            urlList=new ArrayList<String>();
            pagesList = new ArrayList<ScalePageModel>();
            for(int i=0;i<imageInfo.urls.length;i++){
                String sUrl = imageInfo.urls[i];
                urlList.add(sUrl);

                ScalePageModel spm =new ScalePageModel();
                spm.Page = i+1;
                spm.Name = imageInfo.title;
                spm.Url=sUrl;
                pagesList.add(spm);
            }
        }
        catch (Exception e) {
        }

        try
        {
            CurrPage=imageInfo.curIndex;
            if(CurrPage>DocPages){
                CurrPage=DocPages;
            }
            else if(CurrPage<=0){
                CurrPage=1;
            }
        }
        catch (Exception e) {
            CurrPage=1;
        }

        setContentView(R.layout.activity_scale_images);

        setTitleDisplay(false);
        titlebar_layout_custom_cnx=(LinearLayout)findViewById(R.id.titlebar_layout_custom_cnx);
        titlebar_tv_title_text=(TextView)findViewById(R.id.titlebar_tv_title_text);
        titlebar_tv_title_text.setText(imageInfo.title == null ? "" : imageInfo.title);
        titlebar_tv_title_subtext=(TextView)findViewById(R.id.titlebar_tv_title_subtext);
        titlebar_tv_title_subtext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                VibrateUtil.vibrateShot(ScaleImagesActivity.this);
            }
        });

        titlebar_btn_back=(ImageButton)findViewById(R.id.titlebar_btn_back);
        main_dl=(DrawerLayout)findViewById(R.id.main_dl);


        linearLayoutMainPage=(LinearLayout)findViewById(R.id.linearLayoutMainPage);
        linearLayoutTitlebar=(LinearLayout)findViewById(R.id.linearLayoutTitlebar);

        listView = (ListView)findViewById(R.id.listView);
        main_fl_drawer = (FrameLayout)findViewById(R.id.main_fl_drawer);
        button=(ImageButton)findViewById(R.id.button);


        titlebar_btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                VibrateUtil.vibrateShot(ScaleImagesActivity.this);
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                main_dl.openDrawer(main_fl_drawer);
            }
        });

        /////////////////
        indicator=(CirclePageIndicator)findViewById(R.id.indicator);
        indicator.setVisibility(View.GONE);
        mViewPager = new HackyViewPager(this);

        linearLayoutMainPage.addView(mViewPager);

        mViewPager.setAdapter(new ScaleImagePagerAdapter(urlList));
        mViewPager.setOffscreenPageLimit(1);

        //只有 minNavigationPage 张图片才有导航,fileInfo!=null表示能下载
        if(DocPages>minNavigationPage || fileInfo!=null){
            spAdapter = new ScalePagesAdapter(pagesList);
            listView.setAdapter(spAdapter);
            listView.setOnScrollListener(new PauseOnScrollListener(getBitmapLoader(), true, true));
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ScalePageModel item = (ScalePageModel) parent.getAdapter().getItem(position);
                    CurrPage = item.Page;

                    main_dl.setDrawerListener(new DrawerLayout.DrawerListener() {
                        @Override
                        public void onDrawerSlide(View drawerView, float slideOffset) {

                        }

                        @Override
                        public void onDrawerOpened(View drawerView) {

                        }

                        @Override
                        public void onDrawerClosed(View drawerView) {

                            mViewPager.setCurrentItem(CurrPage - 1, false);
                        }

                        @Override
                        public void onDrawerStateChanged(int newState) {

                        }
                    });
                    main_dl.closeDrawer(main_fl_drawer);

                }
            });

            mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    CurrPage = arg0 + 1;
                    titlebar_tv_title_subtext.setText(CurrPage + "/" + DocPages);
                    if (DocPages > minNavigationPage && spAdapter != null && listView != null) {
                        spAdapter.selectItme(arg0);

                        listView.setSelection(arg0==0?0:arg0-1);
                    }


                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                }
            });

            mViewPager.setCurrentItem(CurrPage - 1, false);
            spAdapter.selectItme(CurrPage - 1);
            if(CurrPage==1 && DocPages==1){
                titlebar_tv_title_subtext.setVisibility(View.GONE);
                button.setVisibility(View.GONE);
                main_dl.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }
            else{
                titlebar_tv_title_subtext.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
            }
            titlebar_tv_title_subtext.setText(CurrPage + "/" + DocPages);
        }
        else if(DocPages==1){
            //只有一页
            main_dl.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            titlebar_tv_title_subtext.setText("");
            button.setVisibility(View.GONE);
            linearLayoutTitlebar.setVisibility(View.GONE);

        }
        else
        {
            //小于等于minNavigationPage
            indicator.setVisibility(View.VISIBLE);
            indicator.setViewPager(mViewPager);
            //
            main_dl.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            titlebar_tv_title_subtext.setText("");
            button.setVisibility(View.GONE);
            linearLayoutTitlebar.setVisibility(View.GONE);
        }

    }
    public FileInfo getFileInfo() {
        return fileInfo;
    }

    public ImageInfo getImageInfo() {
        return imageInfo;
    }
    /**
     * 得到自定义右边按钮
     * @return
     */
    public LinearLayout getRightCustom(){
        return titlebar_layout_custom_cnx;
    }

    @Override
    public void onBackPressed() {

        if(main_dl.isDrawerOpen(main_fl_drawer)){
            main_dl.closeDrawer(main_fl_drawer);
        }
        else{
            super.onBackPressed();
            overridePendingTransition(R.anim.anim_scale_in, R.anim.anim_scale_out);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    class ScalePagesAdapter extends BaseAdapter {
        List<ScalePageModel> data=null;
        public ScalePagesAdapter(){
            this.data=new ArrayList<ScalePageModel>();
        }
        public ScalePagesAdapter(List<ScalePageModel> data){
            this.data=data;
        }
        public void add(List<ScalePageModel> data){
            if(this.data!=null){
                this.data.addAll(data);
                notifyDataSetChanged();
            }
        }
        @Override
        public int getCount() {
            if(this.data!=null){
                return this.data.size();
            }
            else{
                return 0;
            }

        }

        public void selectItme(int position) {

            for(ScalePageModel spm : data){
                spm.isSelect=false;

                if(spm.Page-1 == position){
                    spm.isSelect=true;
                }
            }
            notifyDataSetChanged();
            return;
        }

        @Override
        public ScalePageModel getItem(int position) {
            if(this.data!=null){
                return this.data.get(position);
            }
            else{
                return null;
            }

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (null == convertView) {
                convertView = getLayoutInflater().inflate(R.layout.adapter_scale_images_page_item, null);

                viewHolder = new ViewHolder();
                viewHolder.text = (TextView)convertView.findViewById(R.id.textView);
                viewHolder.image = (ImageView)convertView.findViewById(R.id.imageView);
                viewHolder.progress= (ProgressView)convertView.findViewById(R.id.progressBanner);

                viewHolder.image.setTag(viewHolder);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }


            ScalePageModel model = getItem(position);

            viewHolder.text.setText(model.Page+"");

            getBitmapLoader().display(viewHolder.image, UIHttpURL.getWebSiteFullUrl(model.Url), new BitmapLoadCallBack<ImageView>() {
                @Override
                public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                    imageView.setImageBitmap(bitmap);

                    if(imageView.getTag()!=null){
                        try{
                            ViewHolder viewHolder = (ViewHolder) imageView.getTag();
                            viewHolder.progress.setVisibility(View.GONE);
                            viewHolder.image.setVisibility(View.VISIBLE);

                            viewHolder.progress.stop();
                            viewHolder.image.clearAnimation();
                            viewHolder.image.startAnimation(UIApplication.getAnimationSet());

                        }
                        catch (Exception e){
                            LogUtils.e(e.getMessage()+"");
                        }
                    }
                }

                @Override
                public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                    if(imageView.getTag()!=null){
                        try{
//                            imageView.setd
                            ViewHolder viewHolder = (ViewHolder) imageView.getTag();
                            viewHolder.progress.setVisibility(View.GONE);
                            viewHolder.image.setVisibility(View.VISIBLE);
                            viewHolder.progress.stop();
                        }
                        catch (Exception e){
                            LogUtils.e(e.getMessage()+"");
                        }
                    }
                }

                @Override
                public void onLoadStarted(ImageView imageView, String uri, BitmapDisplayConfig config) {
                    super.onLoadStarted(imageView, uri, config);
                    if(imageView.getTag()!=null){
                        try{
                            ViewHolder viewHolder = (ViewHolder) imageView.getTag();
                            viewHolder.progress.setVisibility(View.VISIBLE);
                            viewHolder.image.setVisibility(View.GONE);
                            viewHolder.progress.start();
                        }
                        catch (Exception e){
                            LogUtils.e(e.getMessage()+"");
                        }
                    }
                }
            });

            if(model.isSelect){
                viewHolder.text.setTextColor(Color.parseColor("#0D8ABF"));
                viewHolder.text.setTextSize(28);
            }
            else{
                viewHolder.text.setTextColor(Color.parseColor("#cccccc"));
                viewHolder.text.setTextSize(15);
            }

            return convertView;
        }

    }

    class ViewHolder {
        ProgressView progress;
        ImageView image;
        TextView text;
    }

    class ScaleImagePagerAdapter extends PagerAdapter {
        List<String> data;
        public ScaleImagePagerAdapter(List<String> list){
            this.data=list;
        }

        @Override
        public int getCount() {
            if(this.data!=null && data.size()>0){
                return data.size();
            }
            else{
                return 0;
            }

        }

        public String getItem(int position) {
            if(this.data!=null){
                return this.data.get(position);
            }
            else{
                return null;
            }

        }
        public void displayImage(final String url,PhotoView photoView, final ProgressView progressBanner, final LinearLayout linearLayoutError){


            getBitmapLoader().display(photoView, url, new BitmapLoadCallBack<PhotoView>() {
                @Override
                public void onLoadCompleted(PhotoView container, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {

                    try{
                        progressBanner.stop();
                    }
                    catch (Exception e){
                        LogUtils.e(e.getMessage()+"");
                    }

                    progressBanner.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.GONE);
                    container.setVisibility(View.VISIBLE);
                    container.setImageBitmap(bitmap);
                    container.clearAnimation();
                    container.startAnimation(UIApplication.getAnimationSet());

                    container.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            VibrateUtil.vibrateShot(ScaleImagesActivity.this);
                            final android.app.Dialog dialog = showSimpleCustomDialogMessage(R.layout.scale_images_dialog, false);
                            if (dialog != null) {
                                com.rey.material.widget.Button buttonCallPhone = (com.rey.material.widget.Button) dialog
                                        .findViewById(R.id.buttonSaveImage);
                                buttonCallPhone.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //保存图片
//
                                        String path = SdCardUtil.getSdDCIMCamera()+new MD5FileNameGenerator().generate(url)+".jpg";
                                        try{
                                            File srcFile = getBitmapLoader().getBitmapFileFromDiskCache(url);
                                            File toFile = new File(path);
                                            if(toFile.exists()){
                                                MessageUtil.showShortToast(ScaleImagesActivity.this, "已经下载过此项");
                                            }
                                            else{
                                                FileUtils.copyFile(srcFile,toFile);
                                                MessageUtil.showShortToast(ScaleImagesActivity.this,"保存到:"+path);
                                            }

                                        }
                                        catch (Exception e){
                                            LogUtils.e(e.getMessage()+"");
                                            MessageUtil.showShortToast(ScaleImagesActivity.this, "保存失败");
                                        }

                                        //
                                        dialog.dismiss();
                                    }
                                });


                                com.rey.material.widget.Button buttonCancel = (com.rey.material.widget.Button) dialog
                                        .findViewById(R.id.buttonCancel);
                                buttonCancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                            }
                            return false;
                        }
                    });
                }

                @Override
                public void onLoadFailed(PhotoView container, String s, Drawable drawable) {
                    LogUtils.e(s + "");
                    try{
                        progressBanner.stop();
                    }
                    catch (Exception e){
                        LogUtils.e(e.getMessage()+"");
                    }

                    progressBanner.setVisibility(View.GONE);
                    container.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadStarted(PhotoView container, String uri, BitmapDisplayConfig config) {
                    super.onLoadStarted(container, uri, config);
                    try{
                        progressBanner.setProgress(0.2f);
                        progressBanner.start();
                    }
                    catch (Exception e){
                        LogUtils.e(e.getMessage()+"");
                    }

                    progressBanner.setVisibility(View.VISIBLE);
                    container.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.GONE);
                }

                @Override
                public void onLoading(PhotoView container, String uri, BitmapDisplayConfig config, long total, long current) {
                    super.onLoading(container, uri, config, total, current);
                    try{
                        float percent = ((float)current)/total;
                        if(percent<0.2){
                            progressBanner.setProgress(percent);
                        }
                        //LogUtils.e("百分百:"+percent+"%");
                    }
                    catch (Exception e){
                        LogUtils.e(e.getMessage()+"");
                    }

                    progressBanner.setVisibility(View.VISIBLE);
                    container.setVisibility(View.GONE);
                    linearLayoutError.setVisibility(View.GONE);
                }

            });

        }

        @Override
        public View instantiateItem( final ViewGroup container, int position) {
            final String url = getItem(position);
            //这里得到布局
            View convertView = getLayoutInflater().inflate(R.layout.adapter_scale_image_viewpager_item, null);

            final PhotoView photoView = (PhotoView)convertView.findViewById(R.id.iv_photo);
            photoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                @Override
                public void onViewTap(View view, float v, float v1) {
                    if(DocPages>minNavigationPage || fileInfo!=null){
                        F = !F;
                        if (F) {
                            linearLayoutTitlebar.setVisibility(View.VISIBLE);
                            //linearLayoutMainPage.setBackgroundColor(getResources().getColor(R.color.transparent));
                        } else {
                            linearLayoutTitlebar.setVisibility(View.GONE);
                            //linearLayoutMainPage.setBackgroundColor(getResources().getColor(R.color.black));
                        }
                    }
                    else
                    {
                        //小于minNavigationPage
                        onBackPressed();
                        VibrateUtil.vibrateShot(ScaleImagesActivity.this);
                    }

                }
            });

            final ProgressView progressBanner= (ProgressView)convertView.findViewById(R.id.progressBanner);
            final LinearLayout linearLayoutError=(LinearLayout)convertView.findViewById(R.id.linearLayoutError);
            final Button buttonError= (Button)convertView.findViewById(R.id.buttonError);
            buttonError.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String,String> map =new HashMap();
                    map.put("androidTime",new Date().getTime()+"");

                    displayImage(UIHttpURL.getWebSiteFullUrl(url,map), photoView, progressBanner, linearLayoutError);
                }
            });
            //buttonError.performClick();
            displayImage(UIHttpURL.getWebSiteFullUrl(url), photoView, progressBanner, linearLayoutError);

            container.addView(convertView);
            return convertView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }


    }

}
